<?php

// --------------------------------------------------------------------- //
// FLASH                                                                 //
// Add a record V1.1 build 20030513                                      //
// --------------------------------------------------------------------- //
// IN:  username,password1, password2,firstname,surname,email,company,   //
//      address, telephone, admin, active, expiry, module                //
// OUT: add = "true" | "false", message                                  //
// --------------------------------------------------------------------- //
// NOTES: - you may need to edit the $changelogFile variable to point to //
//          a directory with read/write access for PHP                   //
//                                                                       //
// Changelog:                                                            //
//	- simplified a bit 'module' verification                         //
// --------------------------------------------------------------------- //

    // connection variables -----------------------------------------------
    $mysqlServer   = "66.226.14.61";
    $mysqlUser     = "timescape";
    $mysqlPassword = "ducati748";
    $mysqlDatabase = "timescape";
    $mysqlTable    = "german";


    $changelogFile = "./logs/changes.txt";
    $changelogSize = 1000;

    // Messages -----------------------------------------------------------
    $errorConnect     = 'Unable to connect to database server.';
    $errorConnectdb   = 'Unable to use the database.';
    $errorQuery       = 'Error while accessing the database. It may be corrupted.';
    $errorIdentity    = 'Error while establishing your identity.';

    $errorNoPassword  = 'The Password field may not be empty';
    $errorPasswords   = 'The passwords submitted do not match';
    $errorPassLength  = 'The password must be between 6 and 10 characters long';
    $errorNoUsername  = 'Username is required and must be between 5 and 10 characters long';
    $errorNoFirstName = 'First Name is required';
    $errorNoSurname   = 'Surname is required';
    $errorNoAdmin     = 'Security Level is required';
    $errorNoActive    = 'Account Status is required';
    $errorNoExpiry    = 'Account Expiration is required';
    $errorNoModule    = 'Access Module is required';
    $errorUsername    = 'The Username already exists. Please choose a different one';
    $errorInsert      = 'There was an unknown error while adding the user.';

    $msgInsert        = 'The user was successfully added';

    // Append the Log File ------------------------------------------------
    function appendChangeLog($action)
    {
        global $changelogFile, $changelogSize, $inputUser, $HTTP_SERVER_VARS;
        $userIP    = $HTTP_SERVER_VARS['REMOTE_ADDR'];
        $timeStamp = date("Y-m-d,H:i:s");
        $logEntry  = "$userIP,$inputUser,$timeStamp,$action\r\n";

        if ((@file_exists($changelogFile)) && (@filesize($changelogFile)<$changelogSize))
            $fp = @fopen($changelogFile, "a");
        else
            $fp = @fopen($changelogFile, "w");
        if ($fp != false)
        {
            @flock($fp, LOCK_EX);
            @fwrite($fp, $logEntry);
            @fclose($fp);
        }
    }

    // retrieve session variables if they exist ---------------------------
    session_start();
    $inputUser  = isset($HTTP_SESSION_VARS['inputUser']) ? $HTTP_SESSION_VARS['inputUser'] : "";
    $inputPass  = isset($HTTP_SESSION_VARS['inputPass']) ? $HTTP_SESSION_VARS['inputPass'] : "";

    // MySQL queries ------------------------------------------------------
    $verifyAdminQuery = "SELECT
                         admin, active
                         FROM $mysqlTable
                         WHERE username='$inputUser' AND password='$inputPass'";

    // connect to database ------------------------------------------------
    $dblink = @mysql_connect($mysqlServer, $mysqlUser, $mysqlPassword);
    if ($dblink == false)
    {
        echo "&added=false&message=$errorConnect&";
        exit;
    }

    if (@mysql_select_db($mysqlDatabase) == false)
    {
        echo "&added=false&message=$errorConnectdb&";
        exit;
    }

    // verify that the logged-in user is administrator/active -------------
    $resultQuery = @mysql_query($verifyAdminQuery);
    if ($resultQuery == false)
    {
        echo "&added=false&message=$errorIdentity&";
        exit;
    }
    $numberOfUsers = mysql_num_rows($resultQuery);
    if ($numberOfUsers != 1)
    {
        echo "&added=false&message=$errorIdentity&";
        exit;
    }
    $security = mysql_fetch_array($resultQuery);
    if (($security['admin'] != 'Y') || ($security['active'] != 'Y'))
    {
        echo "&added=false&message=$errorIdentity&";
        exit;
    }

    // init/reset vars - just in case they were automatically parsed ------
    $username   = "";
    $password1  = "";
    $password2  = "";
    $firstname  = "";
    $surname    = "";
    $email      = "";
    $company    = "";
    $address    = "";
    $telephone  = "";
    $admin      = "";
    $active     = "";
    $expiry     = "";
    $module     = "";

    // test for username --------------------------------------------------
    if ((!isset($HTTP_GET_VARS['username'])) || (strlen($HTTP_GET_VARS['username'])<5) || (strlen($HTTP_GET_VARS['username'])>10))
    {
        echo "&added=false&message=$errorNoUsername&";
        exit;
    }
    $username = $HTTP_GET_VARS['username'];

    // test for passwords -------------------------------------------------
    if ((!isset($HTTP_GET_VARS['password1'])) || (!isset($HTTP_GET_VARS['password2'])))
    {
        echo "&added=false&message=$errorNoPassword&";
        exit;
    }
    elseif ($HTTP_GET_VARS['password1'] != $HTTP_GET_VARS['password2'])
    {
        echo "&added=false&message=$errorPasswords&";
        exit;
    }
    elseif ((strlen($HTTP_GET_VARS['password1'])<6) || (strlen($HTTP_GET_VARS['password1'])>10))
    {
        echo "&added=false&message=$errorPassLength&";
        exit;
    }
    $password = $HTTP_GET_VARS['password1'];

    // test for first name ------------------------------------------------
    if ((!isset($HTTP_GET_VARS['firstname'])) || (strlen($HTTP_GET_VARS['firstname'])<1))
    {
        echo "&added=false&message=$errorNoFirstName&";
        exit;
    }
    $firstname = $HTTP_GET_VARS['firstname'];

    // test for surname ---------------------------------------------------
    if ((!isset($HTTP_GET_VARS['surname'])) || (strlen($HTTP_GET_VARS['surname'])<1))
    {
        echo "&added=false&message=$errorNoSurname&";
        exit;
    }
    $surname = $HTTP_GET_VARS['surname'];

    // test for admin status ----------------------------------------------
    if ((!isset($HTTP_GET_VARS['admin'])) || (($HTTP_GET_VARS['admin'] != "Y") && ($HTTP_GET_VARS['admin'] != "N")))
    {
        echo "&added=false&message=$errorNoAdmin&";
        exit;
    }
    $admin = $HTTP_GET_VARS['admin'];

    // test for active status ---------------------------------------------
    if ((!isset($HTTP_GET_VARS['active'])) || (($HTTP_GET_VARS['active'] != "Y") && ($HTTP_GET_VARS['active'] != "N")))
    {
        echo "&added=false&message=$errorNoActive&";
        exit;
    }
    $active = $HTTP_GET_VARS['active'];

    // test for module ----------------------------------------------------
    if (!isset($HTTP_GET_VARS['module']))
    {
        echo "&added=false&message=$errorNoModule&";
        exit;
    }
    $module = $HTTP_GET_VARS['module'];

    // test for expiry ----------------------------------------------------
    if (!isset($HTTP_GET_VARS['expiry']))
    {
        echo "&added=false&message=$errorNoExpiry&";
        exit;
    }

    // compute when the account will expire (could be done by MySQL) ------
    $timestamp = mktime (0,0,0,date("m"),date("d")+$HTTP_GET_VARS['expiry'],date("Y"));
    if (!$timestamp)
        $timestamp = mktime (0,0,0,date("m"),date("d")+30,date("Y"));
    $expiry = date ("Y-m-d", $timestamp);

    // process optional data ----------------------------------------------
    if (isset($HTTP_GET_VARS['email']))
        $email = $HTTP_GET_VARS['email'];

    if (isset($HTTP_GET_VARS['company']))
        $company = $HTTP_GET_VARS['company'];

    if (isset($HTTP_GET_VARS['address']))
        $address = $HTTP_GET_VARS['address'];

    if (isset($HTTP_GET_VARS['telephone']))
        $telephone = $HTTP_GET_VARS['telephone'];

    // verify that the username doesn't already exist ---------------------

    $verifyUsernameQuery = "SELECT username
                            FROM $mysqlTable
                            WHERE username='$username'";

    $resultQuery = @mysql_query($verifyUsernameQuery);
    if ($resultQuery == false)
    {
        echo "&added=false&message=$errorQuery&";
        exit;
    }
    $numberOfUsers = mysql_num_rows($resultQuery);
    if ($numberOfUsers != 0)
    {
        echo "&added=false&message=$errorUsername&";
        exit;
    }

    // add the new user ---------------------------------------------------
    $insertQuery = "INSERT INTO $mysqlTable SET
                    username  = '$username',
                    password  = '$password',
                    firstname = '$firstname',
                    surname   = '$surname',
                    email     = '$email',
                    company   = '$company',
                    address   = '$address',
                    telephone = '$telephone',
                    admin     = '$admin',
                    active    = '$active',
                    expiry    = '$expiry',
                    module    = '$module'";

    $resultQuery = mysql_query($insertQuery);
    if (($resultQuery == false) || (mysql_affected_rows() != 1))
    {
        echo "&added=false&message=$errorInsert&";
        exit;
    }

    echo "&added=true&message=$msgInsert&";

    appendChangeLog("Added the user $username");
?>